package com.helsinki.controller;

import com.github.pagehelper.PageInfo;
import com.helsinki.pojo.Product;
import com.helsinki.pojo.Role;
import com.helsinki.pojo.UserInfo;
import com.helsinki.security.ResultInfo;
import com.helsinki.service.UserInfoService;
import com.helsinki.utils.QueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;
    @RequestMapping("/findById")
    public UserInfo findById(String id) {
        return userInfoService.queryById(id);
    }

    @RequestMapping("list")
    @ResponseBody
    public PageInfo<UserInfo> list(@RequestParam(defaultValue = "1") Integer pageNum,
                                  @RequestParam(defaultValue = "10") Integer pageSize) {
        return userInfoService.queryAll(pageNum,pageSize);
    }

    @RequestMapping("findRolesByUid")
    public List<Role> findRolesByUid(String id) {
        return userInfoService.queryRoleByUid(id);
    }

    @RequestMapping("findRoleIdByUId")
    @ResponseBody
    public List<String> findRoleId(@RequestParam String id){
        List<Role> roles = userInfoService.queryRoleByUid(id);
        List<String> ids = new ArrayList<>();
        for (Role role : roles) {
            ids.add(role.getId());
        }
        return ids;
    }

    // 用户添加角色
    @RequestMapping("addRoles")
    public ResultInfo addRoles(@RequestBody QueryVo queryVo){
        int row = userInfoService.addRoles(queryVo.getUserId(), queryVo.getRoleIds());
        ResultInfo info = new ResultInfo();
        info.setFlag(true);
        info.setData(row);
        return info;
    }

    //添加用户
    @RequestMapping("adduser")
    @ResponseBody
    public String addUser(@RequestBody UserInfo userInfo) throws Exception {
        userInfoService.save(userInfo);
        return null;
    }

    //删除用户
    @RequestMapping("/deleteById")
    @ResponseBody
    public String delete(@RequestBody String id){
        userInfoService.deleteById(id);
        return null;
    }

    //修改用户信息
    @RequestMapping("updateUser")
    @ResponseBody
    public String updateUser(@RequestBody UserInfo userInfo) throws Exception {
        userInfoService.update(userInfo);
        return null;
    }

    //更改用户角色
    @RequestMapping("updateUserRole")
    public String updateUserRole(@RequestBody QueryVo queryVo){
        userInfoService.updateUserRole(queryVo);
        return null;
    }
}